package com.cxc.singleton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

/**
 * 测试反射和反序列化破解单例模式
 *
 */
public class TestDemo2 {
	
	public static void main(String[] args) throws Exception {
		SingletonTest s1 = SingletonTest.getInstance();
		SingletonTest s2 = SingletonTest.getInstance();
		
		System.out.println(s1);
		System.out.println(s2);
		
		//通过反射的方式直接调用私有构造器
		Class<SingletonTest> clazz = (Class<SingletonTest>) Class.forName("com.cxc.singleton.SingletonTest");
		Constructor<SingletonTest> c = clazz.getDeclaredConstructor(null);
		c.setAccessible(true);
		SingletonTest   test1 = c.newInstance();
		SingletonTest   test2 = c.newInstance();
		System.out.println(test1);
		System.out.println(test2);
		
		//通过反序列化的方式构造多个对象 
		FileOutputStream fos = new FileOutputStream("d:/test.txt");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(s1);
		oos.close();
		fos.close();
		
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/test.txt"));
		SingletonTest s3 =  (SingletonTest) ois.readObject();
		System.out.println(s3);
		
		
	}
}
